package cn.easier.activity.console.repository;

import cn.easier.activity.console.entity.MessagePostRecord;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface MessagePostRecordRepository extends JpaRepository<MessagePostRecord, Integer>, JpaSpecificationExecutor<MessagePostRecord> {

    @Query(value = "select " +
            "mpr.id, mp.name, mpr.target, mp.post_time, mp.type, mpr.status, mpr.remark " +
            "from message_post_record mpr " +
            "left join message_post mp on mpr.post_id = mp.id " +
            "where (:name is null or mp.name like :name) " +
            "  and (:timeStart is null or mp.post_time >= :timeStart) " +
            "  and (:timeEnd is null or mp.post_time <= :timeEnd) " +
            "  and (:type is null or mp.type = :type) " +
            "  and (:target is null or mpr.target = :target) " +
            "  and (:status is null or mpr.status = :status) " +
            "  and (:creator is null or mp.creator = :creator) " +
            "order by ?#{#pageable}",
            countQuery = "select count(mpr.id) " +
                    "from message_post_record mpr " +
                    "left join message_post mp on mpr.post_id = mp.id " +
                    "where (:name is null or mp.name like :name) " +
                    "  and (:timeStart is null or mp.post_time >= :timeStart) " +
                    "  and (:timeEnd is null or mp.post_time <= :timeEnd) " +
                    "  and (:type is null or mp.type = :type) " +
                    "  and (:target is null or mpr.target = :target) " +
                    "  and (:status is null or mpr.status = :status) " +
                    "  and (:creator is null or mp.creator = :creator) " +
                    "order by ?#{#pageable}",
            nativeQuery = true)
    Page<Object[]> findAll(
            @Param("name") String name,
            @Param("timeStart") String timeStart,
            @Param("timeEnd") String timeEnd,
            @Param("type") Integer type,
            @Param("target") String target,
            @Param("status") Integer status,
            @Param("creator") String creator,
            Pageable pageable);
}
